import { useEffect, useState } from 'react';
import { menusKeys } from 'src/constants';
import { LayoutTypeEnum, MenuModeEnum } from 'src/interface/theme';
import { storage } from 'src/utils/storage';
import { useLocation } from 'react-router-dom';
import { useThemeMenu } from './useThemeMenu';

export default function useMenuSelected() {
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[] | undefined>([]);
  const { mode, collapsed, layoutMode } = useThemeMenu();
  const location = useLocation();

  function checkKeys(cacheKeys: string[]) {
    const existCache = cacheKeys && cacheKeys.length > 0;
    const currentKeys =
      existCache && cacheKeys.includes(location.pathname) ? cacheKeys : [location.pathname];
    setSelectedKeys(currentKeys);
    !existCache && storage.set(menusKeys, [location.pathname]);
    const generatePaths = [] as string[];
    currentKeys.forEach((path) => {
      const keys = path.split('/').filter(Boolean);
      let preIndex = 0;
      for (let i = 0; i < keys.length; i++) {
        generatePaths.push(`${preIndex === i ? '' : keys[preIndex]}/${keys[i]}`);
        preIndex = i;
      }
      return generatePaths;
    });
    changeOpenKeys(generatePaths);
  }

  useEffect(() => {
    const cacheSelected = storage.get(menusKeys) as string[];
    checkKeys(cacheSelected);
  }, [location.pathname, collapsed, layoutMode, mode]);

  function changeOpenKeys(openKeys: string[]) {
    if (mode === MenuModeEnum.Horizontal || layoutMode === LayoutTypeEnum.Top || collapsed) {
      return setOpenKeys(undefined);
    }
    setOpenKeys(openKeys);
  }
  function changeSelectedKey(selectedKeys: string[]) {
    storage.set(menusKeys, selectedKeys);
    setSelectedKeys(selectedKeys);
  }

  return {
    selectedKeys,
    openKeys,
    changeOpenKeys,
    changeSelectedKey,
  };
}
